var newGrowHTML ="";
var echartVar;
var childWeightAndHeightRangDataMin=[];
var childWeightAndHeightRangDataMax=[];
var childGrowth;
var childWeightAndHeightRangData;
$(function(){
	ym.ajax({
		url: "/userChild/getUserChild",
		success: function (data) {
		   	if(data.res == 1){
		   		$('.baobao').html("");
               if(data.obj.length > 0){
					var html ="";
					datas=data.obj;
					sessionStorage.setItem('datas',JSON.stringify(datas));
					for(var i=0;i<data.obj.length;i++){
						if(i == 0){
							html += '<option value="'+data.obj[i].childId+'" data-sex="'+data.obj[i].childSex+'" selected>'+data.obj[i].childRealname+'</option>';
						}else{
							html += '<option value="'+data.obj[i].childId+'" data-sex="'+data.obj[i].childSex+'" >'+data.obj[i].childRealname+'</option>';
						}
		   			}
                    $('.baobao').append(html);
                    var childId = $(".baobao option:selected").val();
			        ones(childId);
			        echartVar=echarts.init(document.getElementById('grow-list'));
			        var  childSex=  $(".baobao option:selected").attr("data-sex");
			        getChildWeightAndHeightRangData(1,childSex);
		   		}else{
		   			window.location.href = "vaccine1.html";
		   			console.log("没有宝宝");
				}
		   	}else{console.log("获取宝宝失败!")}
		}
	});
	
	
	
    /*setTimeout(function (){
        var childId = $(".baobao option:selected").val();
        ones(childId);
        echartVar=echarts.init(document.getElementById('grow-list'));
        var  childSex=  $(".baobao option:selected").attr("data-sex");
        getChildWeightAndHeightRangData(1,childSex);
    },500);*/
   
   
    /*选择宝宝下拉框*/
    $('.baobao').on('change',function(){
        $('#grow-list').html("");
        echartVar.dispose();
        $('#newGrowList').html("");
        $('#heightNumber').val("");
        $('#weightNumber').val("");
        var childId = $(this).val();
        ones(childId);
        var  childSex=  $(".baobao option:selected").attr("data-sex");
        getChildWeightAndHeightRangData(1,childSex);

    })
    function ones(childId){
        ym.ajax({
            url: "/childGrowth/getYmChildGrowth",
            param:{
                childId:childId
            },
            success: function (data) {
            	var growForm = data.obj;
                var growHTML ="";
                if(growForm.length > 0){
                    /*	for (var i = 0; i < growForm.length; i++){
                     growHTML+="<li>"+
                     "<span>时间：<i>"+growForm[i].createTime+"</i></span>"+
                     "<span>身高："+growForm[i].height+"<i>cm</i></span>"+
                     "<span>体重："+growForm[i].weight+"<i>kg</i></span>"+
                     "</li>"
                     }
                     $('#grow-list').append(growHTML);*/
                    echartVar=echarts.init(document.getElementById('grow-list'));
                    childGrowth=growForm;
                    setEchartsOption(growForm,1);
                }else{
                    growHTML = '<li class="am-text-center" style="margin-top:20%">您还没有添加过该宝宝的成长记录哦！</li>';
                    $('#grow-list').html(growHTML);
                }
                ym.ajax({
                    url: "/childGrowth/getNewestYmChildGrowth",
                    param:{
                        childId:childId
                    },
                    success: function (data) {
                        newGrowHTML ="";
						console.log(data);
                        if(data.obj.length > 0){
                            for(var i=0;i<data.obj.length;i++){
                                newGrowHTML+="<li>"+
                                    "<a href='javascript:void(0)'>"+
                                    "<img src='../img/height.png'>"+
                                    "<span class='positionr'>"+
                                    "<i class='bold font18'>"+data.obj[i].height+"cm</i>"+
                                    "<i class='am-padding-left-lg sg'>身高</i>"+
                                    "</span>"+
                                    "</a>"+
                                    "</li>"+
                                    "<li>"+
                                    "<a href='javascript:void(0)'>"+
                                    "<img src='../img/weight.png'>"+
                                    "<span class='positionr'>"+
                                    "<i class='bold font18'>"+data.obj[i].weight+"kg</i>"+
                                    "<i class='am-padding-left-lg sg'>体重</i>"+
                                    "</span>"+
                                    "</a>"+
                                    "</li>";
                                $('#newGrowList').append(newGrowHTML);
                            }
                        }
                    }
                });
            }
        });
    }

    $('body').on('click','.agePeriod>li',function(){
        $(this).addClass('actives').siblings().removeClass('actives');
    })
    /*新增成长记录*/
    $('#addGorwList').click(function(){
        var childId  = $(".baobao option:selected").val();
        var height = $('#heightNumber').val();
        var weight = $('#weightNumber').val();
        if(height == "" || weight == ""){
            $("#height").modal('open');
            setTimeout(function(){
                $("#height").modal('close');
            },1000)
        }else{
            ym.ajax({
                url: "/childGrowth/insertYmChildGrowth",
                param:{
                    childrenId:childId,
                    height:height,
                    weight:weight
                },
                success: function (data) {
                    if(data.res == 1){
                        window.location.href="graph.html";
                    }
                }
            });
        }
    })
});
function setEchartsOption(data,type){
    var titleText='';
    var untit='';
    var standardInterval='';

    if(type==2){
        // 体重
        untit='kg';
        titleText='体重';
    }else{
        //身高
        untit='cm';
        titleText='身高';
    }
    //最小月份
    var splitValueMin= data[0].age.split('岁');
    var minMonth=parseInt(splitValueMin[0])*12+parseInt(splitValueMin[1].split('月')[0]);
    var splitValueMax= data[data.length-1].age.split('岁');
    //最大月份
    var maxMonth=parseInt(splitValueMax[0])*12+parseInt(splitValueMax[1].split('月')[0]);
    var intervalValue=Math.ceil(((maxMonth-minMonth)/data.length)+1);
    childWeightAndHeightRangDataMin= childWeightAndHeightRangDataMin.slice(minMonth,maxMonth+1);
    childWeightAndHeightRangDataMax= childWeightAndHeightRangDataMax.slice(minMonth,maxMonth+1);
    echartVar.setOption({
        dataZoom: [
            {
                type: 'inside',
                xAxisIndex: 0,

            },
            {
                type: 'inside',
                yAxisIndex: 0,
            }
        ],
        title: {
            textStyle:{
                fontSize:13,
            },
            subtext:standardInterval
        },
        tooltip : {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            },
            formatter:function(params){
                var value=params[0].data[0];
                var text;
                if(value>12){
                    var year=Math.floor(value/12);
                    var month=value%12;
                    if(month == 0){
                        text=year+'岁';
                    }else{
                        text=year+'岁'+month+'月';
                    }
                }else{
                    text=value+'月';
                }
                var res='<div><p>'+text+'孩子'+titleText+'数据</p></div>'
                for(var i=0;i<params.length;i++){
                    res+='<p>'+params[i].seriesName+':'+params[i].data[1]+'</p>'
                }
                return res;
            }
        },
        legend: {
            data:['正常'+titleText+'最低值','孩子'+titleText,'正常'+titleText+'最高值'],
            textStyle:{
                fontSize:10
            },
            itemGap:-5,
            itemWidth :25
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis : [
            {
                type : 'value',
                boundaryGap : true,
                min:minMonth-1<0?0:minMonth-1,
                max:maxMonth,
                interval :intervalValue,
                axisLabel:{
                    //  formatter:'{value}月'
                    formatter:function (value,index){
                        var texts=[];
                        if(value>12){
                            var year=Math.floor(value/12);
                            var month=value%12;
                            if(month == 0){
                                texts.unshift(year+'岁');
                            }else{
                                texts.unshift(year+'岁'+month+'月');
                            }
                        }else{
                            texts.unshift(value+'月')
                        }
                        return texts.join('/')
                    },
                }
            }
        ],
        yAxis : [
            {
                type : 'value',
                axisLabel:{
                    formatter:'{value}'+untit
                }
            }
        ],
        series : [
            {
                symbol: "none",
                name:'正常'+titleText+'最低值',
                type:'line',
                roam:true,
                itemStyle:{
                    color:'#FDCBC4',
                },
                data:childWeightAndHeightRangDataMin
            },
            {
                name:'孩子'+titleText,
                type:'line',
                roam:true,
                data:getChildWeightAndHeightData(data,type)
            },
            {
                symbol: "none",
                name:'正常'+titleText+'最高值',
                type:'line',
                roam:true,
                itemStyle:{
                    color:'#1cfd59',
                },
                data:childWeightAndHeightRangDataMax
            },
        ]
    });
}
function getChildWeightAndHeightRangData(type,childSex) {
    ym.ajax({
        url: "/getChildGrowthRepo",
        param:{
            sex:childSex,
        },
        success: function (data) {
            if(data.res == 1){
                var result=data.obj;
                childWeightAndHeightRangData=result;
                childWeightAndHeightRangDataRaceSelection(type,result);

            }
        }
    });
}
function childWeightAndHeightRangDataRaceSelection(type,data){
    childWeightAndHeightRangDataMin=[];
    childWeightAndHeightRangDataMax=[];
    if(type==1){
        for (var i=0,b=data.length;i<b;i++){
            var wegiht=	data[i].weightRang.split("-")
            var min=[data[i].month,wegiht[0]];
            var max=[data[i].month,wegiht[1]];
            childWeightAndHeightRangDataMin.push(min);
            childWeightAndHeightRangDataMax.push(max);
        }
    }else{
        for (var i=0,b=data.length;i<b;i++){
            var height=	data[i].hightRang.split("-")
            var min=[data[i].month,height[0]];
            var max=[data[i].month,height[1]];
            childWeightAndHeightRangDataMin.push(min);
            childWeightAndHeightRangDataMax.push(max);
        }
    }
}
function getChildWeightAndHeightData(data,type){
    var childWeightAndHeightData=[];
    var result =data;
    for(var i=0,b=result.length;i<b;i++){
        var splitvalue= result[i].age.split('岁');
        var month=parseInt(splitvalue[0])*12+parseInt(splitvalue[1].split('月')[0]);
        var temporaryArray=[];
        temporaryArray.push(month);
        if(type==1){
            temporaryArray.push(result[i].height);
        }else{
            temporaryArray.push(result[i].weight);
        }
        childWeightAndHeightData.push(temporaryArray);
    }
    return childWeightAndHeightData;
}

$('.weightAndHeight').on("click",function(){
    var type=$(this).attr("data-value");
    $(this).parent().children().each(function(index,element){
        if($(element).attr("data-value")==type){
            $(element).addClass("activ");
        }else{
            $(element).removeClass("activ");
        }
    });
    echartVar.dispose();
    echartVar=echarts.init(document.getElementById('grow-list'));
    childWeightAndHeightRangDataRaceSelection(type,childWeightAndHeightRangData);
    setEchartsOption(childGrowth,type);
});







